package com.byCreation.t_globe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import uk.co.senab.photoview.PhotoViewAttacher;

import com.byCreatetion.adabter.TglobeAppAdapter;
import com.byCreatetion.adabter.TouchImageView;

import com.byCreation.Control.Control;
import com.byCreation.Profile.TglobeAppActivity;
import com.byCreation.t_globe.R;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;

import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.squareup.picasso.Picasso;


import Myclass.Screen;
import Parser.HttpGetJson;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class PhotoActivity extends Activity implements OnClickListener,OnItemClickListener{

	
	private GridView gridView;
	private ArrayList<HashMap<String, Object>> MyArrList;
	private HashMap<String, Object> map = new HashMap<String, Object>();
	private ProgressDialog mProgressDialog;
	private TglobeAppAdapter adapter;
	
	


	 
	
	
	
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private DisplayImageOptions options;
	
	
	// ===============GoogleAnalytics==============
			private GoogleAnalytics mGaInstance;
			private Tracker mGaTracker;
			// =============================================
			// ===================================googleAnalytics=============================
		@Override
		public void onStart() {
			super.onStart();
			// The rest of your onStart() code.
			EasyTracker.getInstance().activityStart(this); // Add this method.
			mGaTracker.sendView("Photo Screen");

		}

		@Override
		public void onStop() {
			super.onStop();
			// The rest of your onStop() code.
			EasyTracker.getInstance().activityStop(this); // Add this method.

		}

		// =====================================================================	
	
	 
	 private PhotoViewAttacher mAttacher;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_photo);
		
		
		// =============================GoogleAnalytics=========================
				mGaInstance = GoogleAnalytics.getInstance(this);
				mGaTracker = mGaInstance.getTracker(Control.IDGoogleanalytics);	
		
		options = new DisplayImageOptions.Builder()
		.showStubImage(R.drawable.app_icon)
		.showImageForEmptyUri(R.drawable.app_icon)
		.showImageOnFail(R.drawable.app_icon).delayBeforeLoading(100)
		.cacheInMemory().cacheOnDisc()
		.bitmapConfig(Bitmap.Config.RGB_565)
		.displayer(new RoundedBitmapDisplayer(0)).build();
		initImageLoader(PhotoActivity.this);

		
		
		SetListView();
	}

	
	
	private void SetListView()
    {
		    	
		gridView = (GridView)findViewById(R.id.gridView1);
		this.setProgressBarIndeterminateVisibility(true);
		gridView.setOnItemClickListener(this);
			 //=====================ProgressDialog==========================
	    mProgressDialog = new ProgressDialog(this);
	    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);         
	    mProgressDialog.setMessage("Loading......");                       
	    mProgressDialog.setCancelable(false);  

		
	
	    MyArrList = new ArrayList<HashMap<String, Object>>();
		new LoadData().execute();
		
    }
	
	
//	private void Show_Dialog_Photo(int id)
//	{
//
//  		
// 		final Dialog dialog = new Dialog(PhotoActivity.this,android.R.style.Theme_Translucent_NoTitleBar);
// 		//dialog.requestWindowFeature(dialog.getWindow().FEATURE_NO_TITLE);
// 		//dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
// 		dialog.setContentView(R.layout.alertdialog_photo);
// 		
// 		ImageView imageView_photo =(ImageView)dialog.findViewById(R.id.imageView_photo);
// 		try {
//			imageLoader.displayImage(CardDetailActivity.MyArrList_gallery.get(position).get("img").toString(),imageView_photo, options,animateFirstListener);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
// 		
// 		
// 		
////		  mAttacher = new PhotoViewAttacher(imageView_photo);
////		
////       
////         mAttacher.update();
//// 		
// 		
// 		
// 		
//         dialog.setCancelable(true);
//         dialog.show();
//         
//	}
	

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		
	}
	
	public static int index_photo=0;
	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
		
		index_photo=position;
		startActivity(new Intent(PhotoActivity.this,ViewPagerPhotoViewActivity.class));

	}
	
	
	class LoadData extends AsyncTask<Object, Integer, Object> {

		private boolean Cancel=false;
		private String Exception="";
		
		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			Cancel=true;
			super.onCancelled();
		}

		@SuppressWarnings("null")
		@Override
		protected Object doInBackground(Object... params) {

			
			
			Log.e("TG", "page_id:"+Control.page_id);
			
			
			   try {
					
					JSONObject jsonObj=null;
					jsonObj = new JSONObject(HttpGetJson.GetJson(Control.getAPI_GalleryContent(Control.page_id),Control.user,Control.pass));
					

					Log.e("TG", "getAPI_GalleryContent:"+HttpGetJson.GetJson(Control.getAPI_GalleryContent(Control.page_id),Control.user,Control.pass));
					
					JSONObject Data=jsonObj.getJSONObject("data");
					
					JSONArray jsonarray_data=Data.getJSONArray("img");
						
					 for (int i = 0; i <jsonarray_data.length(); i++)
					 { 
						 
						 map = new HashMap<String, Object>();
						 map.put("img",jsonarray_data.getString(i));
							Log.e("TG", "img:"+jsonarray_data.getString(i));

						 
					     MyArrList.add(map);
					 }
					
			   } catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Cancel=true;
					Exception=e.getMessage();
				
			   } catch (Exception e) {
					// TODO: handle exception
					Cancel=true;
				   Exception=e.getMessage();
			   }
			   
			
			
				
			
				 
			return null;
		}

		@Override
		protected void onPreExecute() {

			
			adapter=null;
			
			if (adapter == null) {
				adapter = new TglobeAppAdapter(PhotoActivity.this, MyArrList);
				gridView.setAdapter(adapter);
				
				Log.e("TG", "adapter = new NotiListAdapter(getActivity(), MyArrList);");
				
			}

			
			super.onPreExecute();
		}

		@Override
		public void onProgressUpdate(Integer... progress) {

			Log.e("star", "progressupdate");
			
			
		}

		@Override
		protected void onPostExecute(Object result) {
		
			if(!Cancel)
			{
			
				runOnUiThread (new Thread(new Runnable() { 
		         public void run() {
		                adapter.notifyDataSetChanged();      
		                

						Log.e("TG", " adapter.notifyDataSetChanged();  ");
		         }
				}));
			}
			else
				Toast.makeText(PhotoActivity.this, Exception, 2000).show();
			
		}

	}



	
	public void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you
		// may tune some of them,
		// or you can create default configuration by
		// ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				context)
				.memoryCacheExtraOptions(800, 480)
				// default = device screen dimensions
				.threadPoolSize(3)
				// default
				.threadPriority(Thread.NORM_PRIORITY - 1)
				// default
				.tasksProcessingOrder(QueueProcessingType.FIFO)
				// default
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
				.memoryCacheSize(2 * 1024 * 1024)
				.discCacheSize(50 * 1024 * 1024).discCacheFileCount(100)
				.discCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
				.imageDownloader(new BaseImageDownloader(context)) // default

				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}

	@SuppressWarnings("unused")
	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {

		final static List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				//if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					//displayedImages.add(imageUri);
				//}
			}
		}
	}


}
